package com.yanwq.nwa.im;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yanwq.nwa.MApplication;
import com.yanwq.nwa.entity.Message;
import com.yanwq.nwa.event.MessageEvent;

import org.greenrobot.eventbus.EventBus;

public class ChatService extends Service {
    public ChatService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Connector.getInstance().connect();
        Connector.getInstance().heartbeat();
        EventMgr.getInstance().registerEventCallback(messageCallback);
        return super.onStartCommand(intent, flags, startId);
    }

    private EventCallback messageCallback = new EventCallback() {
        @Override
        public void onSuccess(String message) {
            JSONObject jsonObject = JSON.parseObject(message);

            if (jsonObject.getString("event").equalsIgnoreCase("message")) {
                Message mb = JSON.parseObject(message, Message.class);
                MApplication.getDaoSession().getMessageDao().insert(mb);

                MessageEvent event = new MessageEvent();
                event.setData(jsonObject);
                EventBus.getDefault().post(event);
            }

        }

        @Override
        public void onFailure(Failure failure) {

        }
    };
}
